package com.zyasdk.service;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.zyasdk.model.ARModel;
import com.zyasdk.model.ServiceModel;
import com.zyasdk.util.JSONHelper;
import com.zyasdk.util.ZYALogUtils;
import com.zyasdk.util.StaticSetting;

import org.apache.http.NameValuePair;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Wiley
 */
public class ServiceTask {
	private static int MAX_SUB_COUNT = 2;//默认提交2次
	private static int INTERVAL_MINUTE = 10;// 间隔10分钟提交一次
	public static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());// 创建线程池，设定允许执行的最大线程数

	/**
	 * 添加任务
	 * 
	 * @param url
	 *            提交地址
	 * @param params
	 *            提交参数
	 * @param handler
	 *            回调
	 */
	public static void addTask(String url, List<NameValuePair> params,
			Handler handler) {
		addTask(url, params, MAX_SUB_COUNT, handler, null);
	}

	/**
	 * 添加任务
	 * 
	 * @param url
	 *            提交地址
	 * @param params
	 *            提交参数
	 */
	public static void addTask(String url, List<NameValuePair> params) {
		addTask(url, params, MAX_SUB_COUNT, null, null);
	}

	/**
	 * 添加任务
	 * 
	 * @param url
	 *            调地址
	 * @param params
	 *            提交参数
	 * @param subCount
	 *            失败后重复提交次数
	 * @param handler
	 *            回调
	 * @param object
	 *            传递参数（配合handler使用，可从Message的obj字段获取）
	 */
	public static void addTask(String url, List<NameValuePair> params,
			int subCount, Handler handler, Object object) {
		Log.i("result", "addTask " +url+"~"+ JSONHelper.toJSON(params));
		ServiceModel sm = new ServiceModel();
		sm.setUrl(url);
		sm.setParams(params);
		sm.setHandler(handler);
		sm.setMaxSubCount(subCount);
		sm.setObject(object);
		executeTask(sm);
	}

	/**
	 * 执行任务
	 * 
	 * @param smodel
	 */
	private static void executeTask(final ServiceModel smodel) {
		if (smodel == null)
			return;
		fixedThreadPool.execute(new Runnable() {
			public void run() {
				String taskName = smodel.getUrl().substring(
						smodel.getUrl().lastIndexOf("/") + 1);
				try {
					while (true) {
						// 执行提交
						String result = WS.GetResponse(smodel.getUrl(),
								smodel.getParams());
						if (result == null) {
							// 每提交失败一次累加一次提交数量
							smodel.setSubCount(smodel.getSubCount() + 1);
							// 如果当前提交的次数已经等于设定的最大提交次数则放弃该任务
							if (smodel.getSubCount() >= smodel.getMaxSubCount()) {
								if (smodel.getHandler() != null)
									smodel.getHandler().sendEmptyMessage(
											StaticSetting.RESULT_ERROR);
								break;
							}
							//如果设置了失败后重复提交则让线程睡眠，唤醒后执行下次提交
							Thread.sleep(INTERVAL_MINUTE * 60 * 1000);
						} else {
							// 提交成功直接完成任务
							if (smodel.getHandler() != null) {
								JSONObject object = new JSONObject(result);
								ARModel model = getARModel(object);
								Bundle bundle = new Bundle();
								bundle.putSerializable("result", model);
								Message message = new Message();
								message.what = StaticSetting.RESULT_OK;
								message.obj = smodel.getObject();
								message.setData(bundle);
								smodel.getHandler().sendMessage(message);
							}
							break;
						}
					}
				} catch (Exception e) {
					ZYALogUtils.e("task " + taskName+" error");
					if (smodel.getHandler() != null)
						smodel.getHandler().sendEmptyMessage(
								StaticSetting.RESULT_ERROR);
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 结果集转换
	 * 
	 * @param object
	 * @return
	 */
	private static ARModel getARModel(JSONObject object) {
		ARModel model = null;
		try {
			if (object != null) {
				model = JSONHelper.parseObject(object, ARModel.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return model;
	}
}
